// pages/index/index.js
var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var QQMapWX = require('../../map/qqmap-wx-jssdk.js');
var qqmapsdk;
var lati = null
var longi = null
var menuUrl = '/pages/nearbyStores/nearbyStores?active='

// 在页面中定义插屏广告对象
var interstitialAd = null;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading:true,
    address:'',
    banner: [],
    showSignIn: false,
    signSuccess:false,
    signFail: false,
    signText:'',
    limit:2,
    page:1,
    newsList:[],
    redPacketAmount:'',
    hotRecommend:[],
    themeList:{},
    vistedNum:'',
    storeList:[],
    keywords:'',
    result:[],
    showSearch:false,
    search_focus:false,
    title:'热门拼团推荐',
    type:[
      { name: '手机通讯', src: '/static/images/index/shoujitongxun.png', url: `${menuUrl}9`},
      { name: '餐饮美食', src: '/static/images/index/canyinmeishi.png', url: `${menuUrl}1`},
      { name: '丽人美容', src: '/static/images/index/meirong.png', url: `${menuUrl}12`},
      { name: '娱乐休闲', src: '/static/images/index/yulehunqing.png', url: `${menuUrl}4`},
      { name: '电器用具', src: '/static/images/index/dianqiyongju.png', url: `${menuUrl}3`},
      { name: '教育培训', src: '/static/images/index/jiaoyupeixun.png', url: `${menuUrl}13`},
      { name: '超市百货', src: '/static/images/index/chaoshibaihuo.png', url: `${menuUrl}2`},
      { name: '旅游出行', src: '/static/images/index/lvyoujiudian.png', url: `${menuUrl}7`},
      { name: '汽车汽修', src: '/static/images/index/qicheqixiu.png', url: `${menuUrl}8`},
      { name: '电脑3C', src: '/static/images/index/diannao.png', url: `${menuUrl}10`},
      { name: '服装鞋包', src: '/static/images/index/fushixiebao.png', url: `${menuUrl}6`},
      { name: '家居生活', src: '/static/images/index/jiajushenghuo.png', url: `${menuUrl}11`},
      { name: '工商服务', src: '/static/images/index/gongshang.png', url: `${menuUrl}14`},
      { name: '家装家政', src: '/static/images/index/jiazheng.png', url: `${menuUrl}15`},
      { name: '婚庆摄影', src: '/static/images/index/sheying.png', url: `${menuUrl}16`},
      { name: '农业特色', src: '/static/images/index/nongye.png', url: `${menuUrl}5`},
      { name: '保险服务', src: '/static/images/index/baoxian.png', url: `${menuUrl}17`},
      { name: '酒店住宿', src: '/static/images/index/jiudian.png', url: `${menuUrl}18`},
    ],
    menu:[{
      menuChild:[
        { name: '', src: '/static/images/index/other/qiandao.png',id:1 },
        { name: '/static/images/index/other/rementuijian.png', src: '/static/images/index/other/remen.png',id:2 },
        { name: '/static/images/index/other/jifenmianfei.png', src: '/static/images/index/other/jifen.png', id: 3 },
      ]
    },{
        menuChild: [
          { name: '/static/images/index/other/fujinhaodian.png', src: '/static/images/index/other/fujin.png', id: 4 },
          { name: '/static/images/index/other/lingjuanzhongxin.png', src: '/static/images/index/other/lingjuan.png', id: 5},
          { name: '/static/images/index/other/lepingo.png', src: '/static/images/index/other/lepingou.png', id: 6 },
        ]
    }],
  },
  goToBusiness(e) {
    // console.log(e)
    let link = e.currentTarget.dataset.item.link
    if(link){
      wx.navigateTo({
        url: `/pages/store/store?storeId=${link}`,
      })
    }
  },
  specialGoToBusiness(e){
    let link = e.currentTarget.dataset.item.avatar
    if (link) {
      wx.navigateTo({
        url: `/pages/store/store?storeId=${link}`,
      })
    }
  },
  menuClick(e){
    let id = e.currentTarget.dataset.item.id
    if(id == 1){
      this.SignIn()
    }
    if(id == 2){
      wx.navigateTo({
        url: '/pages/goodsList/goodsList',
      })
    }
    if(id == 3){
      wx.navigateTo({
        url: '/pages/goodsListItem/goodsListItem?type=0',
      })
    }
    if (id == 4) {
      wx.navigateTo({
        url: '/pages/nearbyStores/nearbyStores',
      })
    }
    if (id == 5) {
      wx.navigateTo({
        url: '/pages/ticketCenter/ticketCenter',
      })
    }
    if (id == 6) {
      wx.navigateTo({
        url: '/pages/goodsList/goodsList',
      })
    }
  },
  // 打开搜索
  openSearch(){
    this.setData({ 
      showSearch: true,
      search_focus:true
    })
  },
  // 关闭搜索
  onCancel(){
    this.setData({
      showSearch: false,
      search_focus: false
    })
  },
  // 去除首尾的空格
  trim: function (s) {
    return s.replace(/(^\s*)|(\s*$)/g, "");
  },
  //搜索
  onSearchList(event){
    var _this = this
    _this.setData({ keywords: _this.trim(event.detail)})
    let data = { keywords:_this.data.keywords}
    let getInf = (str, key) => str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%');
    util.request(api.search,data).then((res)=>{
      if(res.code == 0){
        res.data.forEach(e=>{
          if(e.type == 1){
            e.typeText = '商品'
            e.url = `/pages/join/join?id=${e.id}&type=self`
          }else{
            e.typeText = '门店'
            e.url = `/pages/store/store?storeId=${e.id}`
          }
          //高亮
          var name = e["name"];
          e["name"] = getInf(name, _this.data.keywords);
        })
        _this.setData({result:res.data})
      }
    })
  },

  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // util.getRouter()
    util.getUrl()
    var _this = this
    if (options.inviteUserId != undefined) {
      wx.setStorageSync('inviteUserId', options.inviteUserId)
    }
    // 获取当前的地理位置
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        lati = res.latitude
        longi = res.longitude

        // 实例化API核心类
        var demo = new QQMapWX({
          key: 'NTGBZ-BFCPS-2V3OV-6VPL6-URPC3-FZFEX',//'申请的key'
        });
        // 调用接口,获取用户当前地址
        demo.reverseGeocoder({
          location: {
            latitude: lati,
            longitude: longi
          },
          success: function (res) {
            _this.setData({ address: res.result.address})
          },
          fail: function (res) {
            // console.log(res);
          }
        })
      }
    })

    // 创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-你的广告id'
      })
      //捕捉错误
      interstitialAd.onError(err => {
        console.log(err);
      })
    }
  },
  intoMap(e){
    var item = e.currentTarget.dataset.item
    var storeAddress
    var location
    var myLatitude
    var myLongitude
    // 实例化API核心类
    var demo = new QQMapWX({
      key: 'NTGBZ-BFCPS-2V3OV-6VPL6-URPC3-FZFEX',//'申请的key'
    });
    demo.geocoder({
      address: item.storeAddress,   //用户输入的地址（注：地址中请包含城市名称，否则会影响解析效果），如：'北京市海淀区彩和坊路海淀西大街74号'
      complete: res => {
        storeAddress = res.result.address_components
        location = res.result.location
      }
    });
    
    setTimeout(()=>{
      wx.getLocation({
        type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        success: function (res) {  //因为这里得到的是你当前位置的经纬度
          myLatitude = res.latitude
          myLongitude = res.longitude
          wx.openLocation({        //所以这里会显示你当前的位置
            latitude: location.lat,
            longitude: location.lng,
            name: item.storeAddress,
            address: item.storeAddress,
            scale: 28,
          })
        }
      })
    },500)
  },
  // 签到
  SignIn(){
    var _this = this
    this.setData({ showSignIn:true})
    util.request(api.signIn).then((res=>{
      if(res.errno == 0){
        _this.setData({
          signSuccess:true,
          signFail:false,
        })
        
      }else{
        _this.setData({
          // showSignIn: false,
          signSuccess: false,
          signFail: true,
          signText: res.errmsg,
        })
      }
    }))
  },
  // 关闭签到
  closeSignIn(){
    this.setData({ 
      showSignIn: false,
      signSuccess: false,
      signFail: false
    })
  },
  // banner轮播
  banner(){
    var _this = this
    util.request(api.indexBanner, { position:1}).then((res)=>{
      if(res.errno == 0){
        _this.setData({ banner:res.data.banner})
        // console.log(_this.data.banner)
      }
    })
  },
  newsList(){
    var data = {'limit':this.data.limit,'page':this.data.page}
    var _this = this
    util.request(api.news,data).then((res)=>{
      if(res.code == 0){
        _this.setData({newsList:res.page.list})
      }
    })
  },
  // 热门推荐
  hot(){
    var _this = this
    util.request(api.hotCommend).then((res)=>{
      // console.log('hot',res)
      if(res.errno == 0){
        _this.setData({hotRecommend:res.data.hotGoodsList})
      }else{
        util.alert(res.errmsg)
      }
    })
  },
  //专题精选
  theme(){
    var _this = this
    let data = {'page':1,'size':10}
    util.request(api.themeList,data).then((res)=>{
      // console.log('thenm',res)
      if(res.errno == 0){
        _this.setData({themeList:res.data.data[0]})
      }else{
        util.alert(res.errmsg)
      }
    })
  },
  //新手红包
  getRedPacket(){
    var _this = this

    util.request(api.redPacket).then((res=>{
      if (res.code == 0){
        _this.setData({ 
          redPacketAmount: res.data.hongBao,
          showRedPacket:true,
          showSignIn:true
        })
      }else{
        util.alert(res.msg)
      }
    }))
  },
  closeRedPacket(){
      this.setData({
        showRedPacket: false,
        showSignIn: false
      })
  },
  vistedNum(){
    var _this = this
    util.request(api.vistedNum).then((res)=>{
      if(res.errno ==0){
        _this.setData({ vistedNum:res.data})
      }else{
        util.showErrorToast(res.msg)
      }
    })
  },
  getStoreList() {
    let data = { limit: 2, page: 1  }
    util.request(api.storeList, data).then((res) => {
      if (res.errno == 0) {
        res.data.list.forEach(e => {
          // 获取当前的地理位置
          wx.getLocation({
            type: 'wgs84',
            success: function (res) {
              lati = res.latitude
              longi = res.longitude
              // console.log('我的经纬度', lati, longi)
            }
          })
          // 实例化API核心类
          var qqMap = new QQMapWX({
            key: 'NTGBZ-BFCPS-2V3OV-6VPL6-URPC3-FZFEX',//'申请的key'
          });
          qqMap.geocoder({
            address: e.storeAddress,   //用户输入的地址（注：地址中请包含城市名称，否则会影响解析效果），如：'北京市海淀区彩和坊路海淀西大街74号'
            complete: res => {
              if (res.status == 0){
                // console.log('商家经纬度', res.result.location);   //经纬度对象
                // 计算两地距离
                e.distance = util.getDistance(lati, longi, res.result.location.lat, res.result.location.lng)
              } else {
                util.alert(e.storeAddress + '地址无法解析')
              }
            }
          });
        })
        setTimeout(() => {
          this.setData({ 
            storeList: res.data.list,
            loading:false
          })
        }, 500)
        }else {
        util.showErrorToast(res.mag)
      }
    }).catch((err)=>{
      this.setData({loading:false})
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({ showSignIn: false})
    this.banner()
    this.newsList()
    this.hot()
    this.theme()
    this.vistedNum()
    this.getStoreList()
    // 显示插屏广告
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var _this = this
    // if (options.from == 'button') {
    console.log(`/pages/index/index?&inviteUserId=${wx.getStorageSync('userId')}`)
      return {
        title: '快来看看，这里有大量好货，价格从优~先到先得~！',
        imageUrl: _this.data.banner[0].image_url,
        path: `/pages/index/index?&inviteUserId=${wx.getStorageSync('userId')}`
      }
    // }
  }
})